package top.huhuiyu.spirngboot2.total.service.menu.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.huhuiyu.spirngboot2.total.base.BaseDataResult;
import top.huhuiyu.spirngboot2.total.dao.menu.TbMenusDAO;
import top.huhuiyu.spirngboot2.total.dao.menu.TbUserMenusDAO;
import top.huhuiyu.spirngboot2.total.entity.AuthInfo;
import top.huhuiyu.spirngboot2.total.entity.menu.TbMenus;
import top.huhuiyu.spirngboot2.total.entity.menu.TbUserMenus;
import top.huhuiyu.spirngboot2.total.service.AuthService;
import top.huhuiyu.spirngboot2.total.service.menu.MenuService;
import top.huhuiyu.spirngboot2.total.utils.AuthInfoUtils;
import top.huhuiyu.spirngboot2.total.vo.UserInfo;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MenuServiceImpl implements MenuService {
    private final TbUserMenusDAO tbUserMenusDAO;
    private final TbMenusDAO tbMenusDAO;
    private final AuthService authService;

    @Override
    public BaseDataResult<List<TbMenus>> queryByUser() {
        AuthInfo authInfo = AuthInfoUtils.authInfo();
        UserInfo userInfo = authService.queryById(authInfo.getUserId());

        List<TbUserMenus> userMenus = tbUserMenusDAO.selectList(new QueryWrapper<TbUserMenus>().eq("rid", userInfo.getTbUser().getRole()));
        List<Integer> list = new ArrayList<>();
        userMenus.forEach(tbUserMenus -> list.add(tbUserMenus.getMid()));
        List<TbMenus> menus = tbMenusDAO.selectBatchIds(list);
        return BaseDataResult.ok(menus);
    }

    @Override
    public BaseDataResult<List<TbMenus>> queryByUserTree() {
        List<TbMenus> menus = queryByPid(-1);
        return BaseDataResult.ok(menus);
    }

    @Override
    public List<TbMenus> listToTree(List<TbMenus> menus, Integer pid) {
        List<TbMenus> list = new ArrayList<>();
        menus.forEach(m -> {
            if (m.getPid().equals(pid)) {
                list.add(m);
                m.setSubmenus(listToTree(menus, m.getMid()));
            }
        });
        return list;
    }

    private List<TbMenus> queryByPid(Integer pid) {
        AuthInfo authInfo = AuthInfoUtils.authInfo();
        UserInfo userInfo = authService.queryById(authInfo.getUserId());
        List<TbMenus> menus = tbMenusDAO.queryByPid(pid, userInfo.getTbUser().getRole());
        menus.forEach(tbMenus -> {
            tbMenus.setSubmenus(queryByPid(tbMenus.getMid()));
        });
        return menus;
    }

    @Override
    public BaseDataResult<List<TbMenus>> queryByUser(Integer pid) {
        AuthInfo authInfo = AuthInfoUtils.authInfo();
        UserInfo userInfo = authService.queryById(authInfo.getUserId());
        List<TbMenus> menus = tbMenusDAO.queryByPid(pid, userInfo.getTbUser().getRole());
        return BaseDataResult.ok(menus);
    }

}
